package jee.boot.module.oauth2.auth.verification;

import jee.boot.common.basic.result.MessageCodeHelper;
import jee.boot.common.properties.ProjectConfig;
import jee.boot.common.remote.RemoteEndpoint;
import jee.boot.common.utils.SpringContextHolder;
import jee.boot.common.utils.StringUtils;
import jee.boot.common.utils.VerificationCodeUtil;
import jee.boot.entity.system.SystemConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.provider.TokenRequest;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 图片验证码校验
 */
public class ImageCodeVerification implements AccountVerificationFilter {
    private RedisTemplate<String, Object> redisTemplate;
    private boolean DEFAULT_ENABLE_IMAGE_VERIFICATION_CODE = false;
    public ImageCodeVerification(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    /**
     * 验证是否通过
     *
     * @param context
     * @return 返回false即为不通过, 并终止后面的验证
     */
    @Override
    public void verification(AccountVerificationContext context) throws AccountVerificationException {
        RemoteEndpoint remoteEndpoint = SpringContextHolder.getApplicationContext().getBean(RemoteEndpoint.class);
        ProjectConfig projectConfig = SpringContextHolder.getApplicationContext().getBean(ProjectConfig.class);
        SystemConfig query = new SystemConfig();
        query.setCode("ENABLE_IMAGE_VERIFICATION_CODE");
        SystemConfig config = remoteEndpoint.executePost(projectConfig.getOpenSystemServer(), "/config/getByCode", query, SystemConfig.class);
        boolean enableImg = config.getCode() == null ? DEFAULT_ENABLE_IMAGE_VERIFICATION_CODE : Boolean.parseBoolean(config.getValue());
           if (enableImg) {
            TokenRequest tokenRequest = context.getTokenRequest();
            if (tokenRequest == null) {
                throw new AccountVerificationException(getMessageCodeHelper().getMessage(1111));
            }
            // 获取入参用户名/密码/验证码
            Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
            String pin = parameters.get("pin");
            String pinKey = parameters.get("pinKey");
            if(StringUtils.isNotBlank(pinKey)) {
                boolean checkCode = VerificationCodeUtil.checkCode(pinKey, pin);
                if (!checkCode) {
                    throw new AccountVerificationException(getMessageCodeHelper().getMessage(1113));
                }
            }
        }


    }

    public MessageCodeHelper getMessageCodeHelper() {
        return SpringContextHolder.getApplicationContext().getBean(MessageCodeHelper.class);
    }
}
